//
//  AppDelegate.m
//  LiTingFeng
//
//  Created by xinxuan on 16/1/15.
//  Copyright © 2016年 Bullgo. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarViewController.h"
#import "BGleadPicViewController.h"
#import "MusicsData.h"
#import "PrivateValues.h"
#import "Macro.h"
#import "LaunchDemo.h"
@interface AppDelegate ()

@property (nonatomic, assign) BOOL allowRotation;

@end
   @implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    
    [[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"navigationBackground"] forBarMetrics:UIBarMetricsDefault];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    //如果是第一次启动,将DTLeadPicViewController作为根视图控制器
    if (![[NSUserDefaults standardUserDefaults]  boolForKey:@"firstLaunch"]) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        [MusicsData copyFileDatabase];
//        
        [PrivateValues saveValue:@"NO" forKey:PLIST_IS_MUSIC_PLAYING];
        
        self.window.rootViewController = [[BGleadPicViewController alloc] init];
        
    }else{
        
        //如果不是第一次启动,将DTTableViewController作为根视图控制器
        
        TabBarViewController * rootVC = [[TabBarViewController alloc] init];
        self.window.rootViewController = rootVC;
        
    }
    [self.window makeKeyAndVisible];
    [self openImages];
    // 处理通知
    [self dealLocalNotification:launchOptions];
    
    //对屏幕的旋转做设置
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:@"supportedInterfaceOrientations" object:nil];
    

    return YES;
}


-(void)openImages{
    //获取LaunchScreen.storyborad
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil];
    
    //通过使用storyborardID去获取启动页viewcontroller
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"LaunchScreen"];
    
    //获取viewController的视图
    _launchView = [[UIView alloc]initWithFrame:self.window.frame];
    _launchView = viewController.view;
    
    //把视图添加到window
    [self.window addSubview:_launchView];
     UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.window.frame];
    
    int index = arc4random()%5 + 1;
     imageV.image = [UIImage imageNamed:[NSString stringWithFormat:@"启动图%d",index]];
     [_launchView addSubview:imageV];
    //将图片视图推送到前面
     [self.window bringSubviewToFront:_launchView];
     [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(removeLun) userInfo:nil repeats:NO];
    

}

-(void)removeLun {
    if (self.launchView) {
        [self.launchView removeFromSuperview];
        self.launchView = nil;
    }
}


//通知调用的方法
-(void)change:(NSNotification*)notification{
    
    self.allowRotation = [notification.userInfo[@"surport"] boolValue];
    [self application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:[UIApplication sharedApplication] .keyWindow];
    
}

//禁止横屏
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    
    if (self.allowRotation) {
        return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
    }
    return UIInterfaceOrientationMaskPortrait;
    
    
}


//移除观察者
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"supportedInterfaceOrientations" object:nil];
    
}

#pragma mark -- 处理本地通知
- (void)dealLocalNotification:(NSDictionary *)launchOptions{
    
    // 接受本地通知参数
    /*在iOS8下方弹出通知出现下面的错误:
     Attempting to schedule a local notification with a sound but haven't received permission from the user to badge the application.
     原因是iOS8系统变更了注册方法,需要在applicationDelegate里面注册通知才可以
     */
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    }
    
    UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif)
    {
        
        NSLog(@"Recieved Notification == %@",localNotif);
        NSDictionary* infoDic = localNotif.userInfo;
        NSLog(@"userInfo description == %@",[infoDic description]);
        
    }
    
    
    // 获取本地所有通知
    NSArray *notification = [[UIApplication sharedApplication] scheduledLocalNotifications];
    for (UILocalNotification *notify in notification) {
        
        NSLog(@"获取本地所有通知%@---->", notify);
    }
    
    /*
     //    // 获取系统当前时间
     //    NSDate *date = [NSDate date];
     //    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     //    formatter.dateFormat = @"HH:mm";
     //    NSString *dateString = [formatter stringFromDate:date];
     //
     //    // 发送通知
     //    BOOL flag = [[TXSaveUsrSetting sharedTXSaveUsrSetting] isOff];
     //    NSString *time = [[TXSaveUsrSetting sharedTXSaveUsrSetting] warnTimeString];
     //
     //    if (flag && [time isEqualToString:dateString]) {
     //
     //        NSLog(@"YES--->开启通知");
     //
     //
     //    }else{
     //
     //        NSLog(@"NO --- >移除本地通知");
     //        if (_notication) {
     //
     //            [[UIApplication sharedApplication] cancelLocalNotification:_notication];
     //        }
     //        
     //    }
     //    
     //    NSLog(@"提醒状态:%hhd, 提醒时间%@, 当前时间:%@", flag, time, dateString);
     
     */
    
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
      [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
